//
//  MYPictureSelectorController.swift
//  MYWeibo
//
//  Created by Magic Yu on 16/4/23.
//  Copyright © 2016年 Magic Yu. All rights reserved.
//

import UIKit
import SnapKit
import HMImagePicker

//每个cell之间的间距
private let cellMargin: CGFloat = 3
private let colCount: CGFloat = 4

//图片最多可选张数
private let maxImageCount = 9

private let reuseIdentifier = "Cell"

class MYPictureSelectorController: UICollectionViewController {
    
    //保存添加的图片
    lazy var imageList: [UIImage] = [UIImage]()
    private var selectedAsset:[PHAsset]?
    
    init() {
        
        let layout = UICollectionViewFlowLayout()
        //设置流水布局
        let itemW = (ScreenWidth - (colCount + 1) * cellMargin) / colCount
        layout.minimumInteritemSpacing = cellMargin
        layout.minimumLineSpacing = cellMargin
        layout.itemSize = CGSize(width: itemW, height: itemW)
        layout.sectionInset = UIEdgeInsets(top: cellMargin, left: cellMargin, bottom: 0, right: cellMargin)
        
        super.init(collectionViewLayout: layout)
        collectionView?.backgroundColor = UIColor.whiteColor()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        self.collectionView!.registerClass(PictureSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }
}

extension MYPictureSelectorController {

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        //判断当图片添加满了之后 就不让再添加图片了 只有数组长度不等于图片最多可选张数时 才+1
        let delta = imageList.count >= maxImageCount ? 0 : 1
        return imageList.count + delta
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! PictureSelectorCell
        
        cell.backgroundColor = randomColor()
        //设置代理
       cell.selectedDelegate = self
        
        if indexPath.item == imageList.count {
        cell.image = nil
        }else {
        cell.image = imageList[indexPath.item]
        }
        return cell
    }
    
}
//MARK: 遵守协议
extension MYPictureSelectorController: PictureSelectorDelegate {
    //实现代理方法
    func userWillSelect() {
         //print("vc中 添加图片")
        //图片选择器
        
//        //系统方法
//        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) {
//        
//            let picker = UIImagePickerController()
//            picker.delegate = self
//            //允许对图片进行编辑
//            picker.allowsEditing = true
//            presentViewController(picker, animated: true, completion: nil)
//        }
        //使用框架
        if UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary) {
        
            //使用框架
            let picker = HMImagePickerController(selectedAssets: selectedAsset)
            //设置代理
            picker.pickerDelegate = self
            picker.targetSize = CGSizeMake(600, 600)
            picker.maxPickerCount = maxImageCount
            presentViewController(picker, animated: true, completion: nil)
            
        }
        
    }
    func userWillDelete(cell: PictureSelectorCell) {
        //1.获取用户点击的是哪一个cell
        //2.获取cell对应的indexPath
        if let indexPath = collectionView?.indexPathForCell(cell) {
            
        //3.在数组数据中移除 indexPath.item对应的元素
            imageList.removeAtIndex(indexPath.item)
            
            //删除上一次选择图片的数据源
            self.selectedAsset?.removeAtIndex(indexPath.item)
            
        //4.刷新数据
            collectionView?.reloadData()
        }
    }
    
}

//extension MYPictureSelectorController: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
//
//    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
//        print(image)
//        print(editingInfo)
//        imageList.append(image)
//        
//        //刷新数据
//        self.collectionView?.reloadData()
//        
//        //一旦实现了协议方法后 图片选择器的消失就交给程序员来管理
//        dismissViewControllerAnimated(true, completion: nil)
//    }
//    
//    
//}

extension MYPictureSelectorController: HMImagePickerControllerDelegate {

    func imagePickerController(picker: HMImagePickerController, didFinishSelectedImages images: [UIImage], selectedAssets: [PHAsset]?) {
        
        self.imageList = images
        self.selectedAsset = selectedAssets
        self.collectionView?.reloadData()
        
        dismissViewControllerAnimated(true, completion: nil)
        
        
        
    }
    
}


//MARK: 定义协议
@objc protocol PictureSelectorDelegate: NSObjectProtocol {

    //定义协议方法
    optional func userWillSelect()
    
    optional func userWillDelete(cell: PictureSelectorCell)
    
}

class PictureSelectorCell: UICollectionViewCell {
    
    var image: UIImage? {
        didSet {
        //给按钮设置图片
            deleteBtn.hidden = image == nil
            addBtn.setImage(image, forState: .Normal)
        }
    }
    
    //代理属性
    weak var selectedDelegate: PictureSelectorDelegate?
    
    //按钮点击事件的实现
    @objc private func addBtnClick() {
        //通知代理实现方法
        
        //当已经有图片的时候 就不允许再添加图片了
        if image != nil {
            print("已经有图了,不要再加了")
            return
        }
        selectedDelegate?.userWillSelect?()
    }
    
    @objc private func deleteBtnClick() {
        selectedDelegate?.userWillDelete?(self)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: 设置UI界面
    private func setupUI() {
        
        //添加按钮
        contentView.addSubview(addBtn)
        contentView.addSubview(deleteBtn)
        
        //设置约束
        addBtn.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
        
        deleteBtn.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(contentView.snp_top)
            make.right.equalTo(contentView.snp_right)
        }
        
        //按钮添加点击事件
        addBtn.addTarget(self, action: "addBtnClick", forControlEvents: .TouchUpInside)
        deleteBtn.addTarget(self, action: "deleteBtnClick", forControlEvents: .TouchUpInside)
        
    }
    
    //MARK: 懒加载子视图
    private lazy var addBtn: UIButton = {
    
        let btn = UIButton()
        btn.imageView?.contentMode = .ScaleAspectFill
        btn.setBackgroundImage(UIImage(named: "compose_pic_add"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named: "compose_pic_add_highlighted"), forState: .Highlighted)
        return btn
    }()
    
    private lazy var deleteBtn: UIButton = {
    
        let btn = UIButton()
        btn.setBackgroundImage(UIImage(named: "compose_photo_close"), forState: .Normal)
        return btn
    }()

}




